/**
 * 知识库详情页面，详情展示，附件下载等
 * author:caiyl5
 * date:2016年8月23日16:09
 */
var detail = {
    //分页变量
    pageSize: 5,
    pageNum: 1,
    /**
     * bindEvent 页面事件
     */
    bindEvent: function () {

        $(".next-operation").unbind().on("click", function () {
            summer.closeWin();
        });
        //返回按钮
        $("#toback_detail").unbind().on("click", function () {
            $(".app_knowledge_studio").remove();
            var detailPageFromRout = window.sessionStorage.detailPageFromRout;
            window.location.href = "#" + detailPageFromRout;
        });
        //收藏按钮
        $("#tocollect").unbind().on("click", function () {
            detail.collect();
        });
        //点击输入框
        $("#detail_mask").unbind().on("click", function () {
            //弹出输入框
            $("#aboutCommentDetail").slideUp();
            $("#detail_mask").slideUp();
            $(".footer-input").slideDown();
            $(".footer-input").val("");
        });
        //点击输入框
        $("#detailfooter-input").unbind().on("click", function () {
            //弹出输入框
            $("#aboutCommentDetail").slideDown("slow");
            $("#detail_mask").show();
            $("#comment_content").focus();//使input获取焦点
            $(".footer-input").slideUp();
        });
        //点击输入框取消
        $("#comment_cancel ").unbind().on("click", function () {
            //弹出输入框
            $("#aboutCommentDetail").slideUp();
            $("#detail_mask").slideUp();
            $(".footer-input").slideDown();
            $(".footer-input").val("");
        });
        //点击输入框发送
        $("#comment_commit").unbind().on("click", function () {
            var comment_content = $("#comment_content").val();
            if (comment_content.length < 5) {
                common.showTip('您评论的内容少于5个字');
            } else {
                // {"comment_contant":"一条评论","pk_user":"admin","pk_publish":"3"}
                var param = {
                    "comment_contant": comment_content,
                    "pk_user": window.localStorage.userid,
                    "pk_publish": window.sessionStorage.getItem("product_detail_id")
                };
                //发送评论
                detail.sendComment(param);
            }
        });
    },
    /**
     * 显示图片列表信息
     */
    showPicListFunction: function () {
        var achementList_pic = common.strToJson(window.sessionStorage.achementList_pic);
        var showLength = 9;
        var startIndex = 0;
        if (achementList_pic.length - $(".detailImage").length <= 9) {
            showLength = achementList_pic.length;
            $("#showMorePicDiv").hide();
        }
        if ($(".detailImage").length > 0) {
            startIndex = $(".detailImage").length;
        }
        for (var i = startIndex; i < parseInt(startIndex) + showLength; i++) {//
            var pic = achementList_pic[i];
            var img = new Image();
            var imageWidth = pic.file_measure.split("*")[0];
            var imageHieght = pic.file_measure.split("*")[1];
            //随机数产生
            var randomNum = (Math.random() + "").split(".")[1];
            var imageIndex = "img_" + randomNum;
            var ohtml = '<figure><div><a href="javascript:void(0);" data-size="' + imageWidth + 'x' + imageHieght + '"><img id="' + imageIndex + '" src="images/waiting.gif" width="32px" height="32px" class="loaddingImage"/></a></div></figure>';
            $(".my-gallery").append(ohtml);
            //图片单独下载
            detail.picDownload(pic.pk_attachment, imageIndex);
        }
    },
    /**
     * 图片的异步取得
     */
    picDownload: function (filePk, imageIndex) {
        //请求参数
        var url = "/file/picdownload/" + filePk;
        common.interfaceAjaxFunction(url, "", detail.picDownloadSuccess, true, imageIndex, false, false);
    },
    /**
     * 下载成功
     */
    picDownloadSuccess: function (res, imageIndex) {
        //var imageWidthAndHeight = detail.imgLoad(res);
        //alert("imageWidthAndHeight====" + fileMeasure);
        /*var imageWidthAndHeightSplit = fileMeasure.split("*");*/
        $("#" + imageIndex).attr({
            "src": "data:image/png;base64," + res,
            "width": "30%",
            "height": "4.8rem"
        }).addClass("detailImage");
        $("#" + imageIndex).parent().attr("href", "data:image/png;base64," + res);
        //初始化上拉加载下拉刷新控件
        common.initIscroll("detailListContent", false, detail.pullUpCallBack);
        $script("js/PhotoSwipe/js/photoswipe.js?v=" + version, "photoswipe");
        $script.ready('photoswipe', function () {
            $script("js/PhotoSwipe/js/photoswipe-ui-default.min.js?v=" + version, function () {
                detail.initPhotoSwipeFromDOM(".my-gallery");
            });
        });
    },
    //加载数据
    loadData: function () {
        var param = {
            "pk_user": window.localStorage.userid,
            "pk_publish": window.sessionStorage.getItem("product_detail_id")
        };
        //转圈
        common.showLoading();
        var url = "/kmpublish/App/queryKnowledgeByPK";
        common.interfaceAjaxFunction(url, param, this.queryKnowledgeAttByPKSuccess);

        //初始化图片和附件
        common.showLoading();
        var url = "/kmpublish/App/queryAttByPK";
        common.interfaceAjaxFunction(url, param, this.queryAttByPKSuccess);
        //初始化评论
        detail.initComment();
    },
    queryKnowledgeAttByPKSuccess: function (res) {
        $("#detailListContent").show();
        if (res.status == "0") {
            var data = res.data[0];
            if (!data || data.length == 0) {
                common.showTip("没有数据");
            } else {
                $(".detailTitle").text(data.publish_title);
                publish_time = data.publish_year + "." + data.publish_month + "." + data.publish_day;
                $(".detailTimeLeft").text(publish_time);
                $(".detailTimeright").text(data.publish_user_name);
                $(".detailText").text(data.publish_memo);

                //是否有视频文件
                if (data.studioUrl !== null && data.studioUrl !== undefined && data.studioUrl !== "") {
                    $(".knowledagestudio").css("display", "block");
                    var studioUrlList = data.studioUrl.split(',');
                    var studioHtml = '';
                    for (var i = 0; i < studioUrlList.length; i++) {
                        if (studioUrlList[i] != '' && studioUrlList[i] != undefined && studioUrlList[i] != null) {
                            studioHtml += '<iframe src="' + studioUrlList[i] + '" class="app_knowledge_studio" frameborder=0 allowfullscreen></iframe>'
                        }
                    }
                    $(".knowledagestudio").html(studioHtml);
                }

                if (data.pk_favorite == undefined || data.pk_favorite == "NULL") {
                    //未收藏
                    $("#tocollect img").attr("src", "images/bottom-sc1.png");
                    $("#tocollect").attr("status", "N");
                } else {
                    // 已收藏
                    $("#tocollect img").attr("src", "images/bottom-sc2.png");
                    $("#tocollect").attr("status", "Y");
                }
            }
        } else {
            //给出信息提示
            $("#detailListContent").height($(window).height() - $(".header").height());
            common.show_error(res.message, "detailListContent");
        }
        //common.hideLoading();
        //初始化上拉加载下拉刷新控件
        common.initIscroll("detailListContent", false, detail.pullUpCallBack);
        detail.initDownload();
    },
    /**
     * 附件单独接口取得
     */
    queryAttByPKSuccess: function (res) {
        $("#detailListContent").show();
        if (res.status == "0") {
            var data = res.data[0];
            if (data != undefined) {
                if (data.achementList_pic && data.achementList_pic.length > 0) {
                    //
                    $("detailPictor").show();
                    $(".detailPictorCon").html(" ");
                    //显示图片用的公共函数
                    window.sessionStorage.achementList_pic = JSON.stringify(data.achementList_pic);
                    detail.showPicListFunction();
                } else {
                    $(".detailPictor").hide();
                    $("#showMorePicDiv").hide();
                }
                if (data.achementList_oth && data.achementList_oth.length > 0) {
                    $(".detailAppendix").show();
                    $(".detailPpt-count").html(" ");
                    if (data.achementList_oth.length == 0) {
                        $(".detailAppendix").hide();
                    } else {
                        for (var i = 0; i < data.achementList_oth.length; i++) {
                            var att = data.achementList_oth[i];

                            var fileNameTypeIndex = att.filename.lastIndexOf(".");
                            var fileType = att.filename.substring(parseInt(fileNameTypeIndex) + 1, att.filename.length);

                            var publishtime = att.att_year + "." + att.att_month + "." + att.att_day;
                            var ohtml = '<div class="detailPpt" dataurl="' + att.fileurl + '" fileName= "' + att.fname + '" fileType="' + fileType + '" filePath= "' + att.pk_attachment + '" thisFileSize="' + att.filesize + '">';
                            var imageurl = "images/";
                            switch (fileType.toLowerCase()) {
                                case "docx":
                                case "doc":
                                    imageurl += "word";
                                    break;
                                case "pdf":
                                    imageurl += "pdf";
                                    break;
                                case "xlsx":
                                case "xls":
                                    imageurl += "excel";
                                    break;
                                case "pptx":
                                case "ppt":
                                    imageurl += "ppt";
                                    break;
                                case "mp4":
                                    imageurl += "mp4";
                                    break;
                                default:
                                    imageurl += "other";
                                    break;
                            }
                            imageurl += ".png";
                            ohtml += '<img src="' + imageurl + '"/><div class="detailPptC">'
                                + '<div class="pptTitle"> ' + att.fname + '</div>'
                                + '<div class="pptAuthor"><div class="pptSize">' + att.filesize + '</div><div class="pptTime">' + publishtime + '</div></div>'
                                + '<div id="skill"><div><span class="expand html5" id="' + att.pk_attachment + '" style="display:none;"></span></div></div>'
                                + '</div></div>';
                            $(".detailPpt-count").append(ohtml);

                        }

                    }
                } else {
                    $(".detailAppendix").hide();
                }
            } else {
                $(".detailAppendix").hide();
                $(".detailPictor").hide();
            }
        }//else的时候不给于提示信息
        //common.hideLoading();
        //初始化上拉加载下拉刷新控件
        common.initIscroll("detailListContent", false, detail.pullUpCallBack);
        detail.initDownload();
    },
    //初始化 下载组件
    initDownload: function () {

        $(".detailPpt").unbind().on("click", function () {
            var url = $(this).attr("dataurl");
            var type = $(this).attr("fileType");
            var fileName = $(this).attr("fileName") + "." + type;
            var id = $(this).attr("filePath");
            var filePath = "shellkm" + "/";
            fileName = id + "," + fileName;
            $("#" + id).addClass(id);

            var fileSize = $(this).attr("thisFileSize");

            //判断文件是否已经存在。
            var flag = $file.exists({
                path: filePath,
                file: fileName
            });

            if (flag != "false") {
                //重新记录一次
                detail.recordCurrentUserAttachDownloadFiles(fileName, filePath, id, type, url, fileSize);
                detail.openfile(type, filePath, fileName);
                return false;
            }
            url = common.contextPath() + "/file/appdownloadFile/" + id;
            detail.downloadDocx(url, filePath, fileName);

        });
    },
    //初始化加入一些评论
    initComment: function () {
        // $(".detailCommentContent").remove();
        //获取评论入参
        var param = {
            "pk_publish": window.sessionStorage.getItem("product_detail_id"),
            "pk_user": window.localStorage.userid,
            "pageSize": detail.pageSize,
            "pageNum": detail.pageNum,
            "onlyOne": "0"
        };
        var url = "/comment/app/queryComment";
        common.interfaceAjaxFunction(url, param, detail.queryCommentSuccess, true, "", false);
    },
    /**
     * 查询成功回调
     *
     */
    queryCommentSuccess: function (res) {
        $("#detailCommentContentAll").html("");
        var comment_html = "";
        if (res.status == 0) {
            for (var i = 0; i < res.data.length; i++) {
                var user_name = res.data[i].user_name;
                if (user_name == undefined || user_name == "") {
                    user_name = "匿名";
                }
                var comment_content = res.data[i].comment_contant
                var comment_time = res.data[i].comment_time;

                //用户评论html
                var user_content = '<div class="commentName">' + '<div>' + user_name + '</div>' + '<div class="one-hour">' + comment_time + '</div>' +
                    '</div>' + '<div class="commentImg"><img src="images/reply-icon.png" alt=""/></div>' + '<div class="commentContent">' + comment_content + '</div>';
                //管理员评论html
                var mannager_content = "";
                for (var j = 0; j < res.data[i].data.length; j++) {
                    var user_name1 = res.data[i].data[j].user_name;
                    var comment_time1 = res.data[i].data[j].comment_time;
                    var comment_content1 = res.data[i].data[j].comment_contant;
                    mannager_content += '<div class="mannagerRespose">' + '<div class="commentName">' + '<div>' + '<span>' + user_name1 + '</span>' + '<span class="gray">回复</span>' + '<span>' + user_name + '</span>' +
                        '</div>' + '<div class="one-hour">' + comment_time1 + '</div>' + '</div>' + '<div class="commentImg"><img src="images/reply-icon.png" alt=""/></div>' +
                        '<div class="commentContent">' + comment_content1 + '</div>' + '</div>';
                }
                //所有的评论
                comment_html += '<div class="detailCommentContent">' + user_content + mannager_content + '</div>';
            }
        } else {
            //关闭加载转圈
            common.showTip(res.message);
            //common.show_error(res.message, "aboutCommentDetail");
        }
        //将评论插入到html中
        $("#detailCommentContentAll").append(comment_html);
        //分页功能
        if (res.count > (detail.pageSize * detail.pageNum)) {
            $(".noCommentContent").attr("status", "1");
            $(".noCommentContent").text("上拉加载更多");
        } else if (res.count == 0) {
            $(".noCommentContent").attr("status", "0");
            $(".noCommentContent").text("暂无评论");
        } else {
            $(".noCommentContent").attr("status", "2");
            $(".noCommentContent").text("已加载全部");
        }
        //隐藏加载转圈
        //common.hideLoading();

        //初始化，isocroll
        //common.initIscrollBody("detailListContent");
        //初始化上拉加载下拉刷新控件
        common.initIscroll("detailListContent", false, detail.pullUpCallBack);
        detail.initDownload();

    },


    /**
     * 上拉加载更多
     */
    pullUpCallBack: function () {
        //点击加载更多评论 .status ：  0.暂无评论 1.点击加载更多评论 2.已加载全部评论
        //评论列表状态
        var comment_status = $(".noCommentContent").attr("status");
        if (comment_status == 1) {
            // common.showTip("点击加载更多评论");
            detail.pageNum += 1;
            detail.initComment();
        } else if (comment_status == 2) {
            common.showTip("已加载全部评论");
        }
    },
    /**
     * 发送评论、、
     */
    sendComment: function (res) {
        //转圈
        common.showLoading();
        var url = "/comment/app/addComment";
        common.interfaceAjaxFunction(url, res, this.sendCommentSuccess);
    },
    /**
     * 发送成功回调、、
     */
    sendCommentSuccess: function (res) {
        common.showTip("评论成功");
        //初始化评论
        detail.pageNum = 1;
        $("#detailCommentContentAll").html("");
        detail.initComment();
        // 隐藏输入框
        $("#aboutCommentDetail").slideUp();
        $("#detail_mask").slideUp();
        $(".footer-input").slideDown();
        $("#comment_content").val("");
    },
    /**
     * 收藏功能
     */
    collect: function () {

        var text = $("#tocollect").attr("status");
        if (text == "N") {
            var param = {
                "pk_user": window.localStorage.userid,
                "pk_publish": window.sessionStorage.getItem("product_detail_id")
            };
            //转圈
            common.showLoading();
            var url = "/favorite/App/insertfavorite";
            common.interfaceAjaxFunction(url, param, this.insertfavoriteSuccess, true, "", false);
        } else {
            var param = {
                "pk_user": window.localStorage.userid,
                /*"pk_publish":"1"*/
                "pk_favorite": window.sessionStorage.getItem("product_detail_id")
            };
            //转圈
            common.showLoading();
            var url = "/favorite/App/deletefavorite";
            common.interfaceAjaxFunction(url, param, this.deletefavoriteSuccess, true, "", false);
        }

    },
    //再次进入的时候的处理，防止缓存
    removeStorage: function () {
        var url = "/kmpublish/App/queryKnowledgeByPK";
        var sessionStorageKey = url.replace(/\//g, "").replace(/-/g, "_");
        var param = {
            "pk_user": window.localStorage.userid,
            "pk_publish": window.sessionStorage.getItem("product_detail_id")
        };
        sessionStorageKey += common.getSignString(param);
        window.sessionStorage.removeItem(sessionStorageKey);
    },
    insertfavoriteSuccess: function (res) {
        //common.hideLoading();
        if (res.status == "0") {
            // 已收藏
            $("#tocollect img").attr("src", "images/bottom-sc2.png");
            $("#tocollect").attr("status", "Y");
            detail.removeStorage();
            //修改前页面显示数字
            var currentPK = window.sessionStorage.product_detail_id;
            $("#fr_" + currentPK).html(parseInt($("#fr_" + currentPK).html()) + 1);
            common.showTip("收藏成功");
        } else {
            common.showTip(res.message);
        }
    },
    deletefavoriteSuccess: function (res) {
        if (res.status == "0") {
            $("#tocollect img").attr("src", "images/bottom-sc1.png");
            $("#tocollect").attr("status", "N");
            common.showTip("取消收藏成功");
            //再次进入的时候的处理，防止缓存
            detail.removeStorage();
            //修改前页面显示数字
            var currentPK = window.sessionStorage.product_detail_id;
            $("#fr_" + currentPK).html(parseInt($("#fr_" + currentPK).html()) - 1);
        } else {
            common.showTip("取消收藏失败");
        }
    },
    /**
     * 进行页面路由监听配置，覆盖首页设置的路由
     *
     */
    bindRout: function () {
        //查询结果页面，覆盖路由，不在刷新
        Path.map("#productList").to(function () {
            common.loadPageDiv("html/productList.html", false, true);
        });

        //查询结果页面，覆盖路由，不在刷新
        Path.map("#productList/:status").to(function () {
            common.loadPageDiv("html/productList.html", false, true);
        });
        //产品点击搜索后的触发事件
        Path.map("#productListSearchByInput").to(function () {
            common.loadPageDiv("html/productList.html", false, true);
        });
        //价值文档点击搜索后的触发事件
        Path.map("#knowledgeSearchByInput").to(function () {
            common.loadPageDiv("html/productList.html", false, true);
        });
        //查询结果页面，覆盖路由，刷新
        Path.map("#collectList").to(function () {
            common.loadPageDiv("html/detail.html", false, true);
        });
        Path.listen();
    },
    initPhotoSwipeFromDOM: function (gallerySelector) {
        // 解析来自DOM元素幻灯片数据（URL，标题，大小...）
        // (children of gallerySelector)
        var parseThumbnailElements = function (el) {
            var thumbElements = el.childNodes,
                numNodes = thumbElements.length,
                items = [],
                figureEl,
                linkEl,
                size,
                item,
                divEl;

            for (var i = 0; i < numNodes; i++) {

                figureEl = thumbElements[i]; // <figure> element

                // 仅包括元素节点
                if (figureEl.nodeType !== 1) {
                    continue;
                }
                divEl = figureEl.children[0];
                linkEl = divEl.children[0]; // <a> element

                size = linkEl.getAttribute('data-size').split('x');

                // 创建幻灯片对象
                item = {
                    src: linkEl.getAttribute('href'),
                    w: parseInt(size[0], 10),
                    h: parseInt(size[1], 10)
                };


                if (figureEl.children.length > 1) {
                    // <figcaption> content
                    item.title = figureEl.children[1].innerHTML;
                }

                if (linkEl.children.length > 0) {
                    // <img> 缩略图节点, 检索缩略图网址
                    item.msrc = linkEl.children[0].getAttribute('src');
                }

                item.el = figureEl; // 保存链接元素 for getThumbBoundsFn
                items.push(item);
            }

            return items;
        };

        // 查找最近的父节点
        var closest = function closest(el, fn) {
            return el && ( fn(el) ? el : closest(el.parentNode, fn) );
        };

        // 当用户点击缩略图触发
        var onThumbnailsClick = function (e) {
            e = e || window.event;
            e.preventDefault ? e.preventDefault() : e.returnValue = false;

            var eTarget = e.target || e.srcElement;

            // find root element of slide
            var clickedListItem = closest(eTarget, function (el) {
                return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
            });

            if (!clickedListItem) {
                return;
            }

            // find index of clicked item by looping through all child nodes
            // alternatively, you may define index via data- attribute
            var clickedGallery = clickedListItem.parentNode,
                childNodes = clickedListItem.parentNode.childNodes,
                numChildNodes = childNodes.length,
                nodeIndex = 0,
                index;

            for (var i = 0; i < numChildNodes; i++) {
                if (childNodes[i].nodeType !== 1) {
                    continue;
                }

                if (childNodes[i] === clickedListItem) {
                    index = nodeIndex;
                    break;
                }
                nodeIndex++;
            }


            if (index >= 0) {
                // open PhotoSwipe if valid index found
                openPhotoSwipe(index, clickedGallery);
            }
            return false;
        };

        // parse picture index and gallery index from URL (#&pid=1&gid=2)
        var photoswipeParseHash = function () {
            var hash = window.location.hash.substring(1),
                params = {};

            if (hash.length < 5) {
                return params;
            }

            var vars = hash.split('&');
            for (var i = 0; i < vars.length; i++) {
                if (!vars[i]) {
                    continue;
                }
                var pair = vars[i].split('=');
                if (pair.length < 2) {
                    continue;
                }
                params[pair[0]] = pair[1];
            }

            if (params.gid) {
                params.gid = parseInt(params.gid, 10);
            }

            return params;
        };

        var openPhotoSwipe = function (index, galleryElement, disableAnimation, fromURL) {
            var pswpElement = document.querySelectorAll('.pswp')[0],
                gallery,
                options,
                items;

            items = parseThumbnailElements(galleryElement);

            // 这里可以定义参数
            options = {
                barsSize: {
                    top: 100,
                    bottom: 100
                },
                fullscreenEl: false,
                shareButtons: [
                    {id: 'wechat', label: '分享微信', url: '#'},
                    {id: 'weibo', label: '新浪微博', url: '#'},
                    {id: 'download', label: '保存图片', url: '{{raw_image_url}}', download: true}
                ],

                // define gallery index (for URL)
                galleryUID: galleryElement.getAttribute('data-pswp-uid'),

                getThumbBoundsFn: function (index) {
                    // See Options -> getThumbBoundsFn section of documentation for more info
                    var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                        pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                        rect = thumbnail.getBoundingClientRect();

                    return {x: rect.left, y: rect.top + pageYScroll, w: rect.width};
                }

            };

            // PhotoSwipe opened from URL
            if (fromURL) {
                if (options.galleryPIDs) {
                    // parse real index when custom PIDs are used 
                    for (var j = 0; j < items.length; j++) {
                        if (items[j].pid == index) {
                            options.index = j;
                            break;
                        }
                    }
                } else {
                    // in URL indexes start from 1
                    options.index = parseInt(index, 10) - 1;
                }
            } else {
                options.index = parseInt(index, 10);
            }

            // exit if index not found
            if (isNaN(options.index)) {
                return;
            }

            if (disableAnimation) {
                options.showAnimationDuration = 0;
            }

            // Pass data to PhotoSwipe and initialize it
            gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
            gallery.init();
        };

        // loop through all gallery elements and bind events
        var galleryElements = document.querySelectorAll(gallerySelector);

        for (var i = 0, l = galleryElements.length; i < l; i++) {
            galleryElements[i].setAttribute('data-pswp-uid', i + 1);
            galleryElements[i].onclick = onThumbnailsClick;
        }

        // Parse URL and open gallery if it contains #&pid=3&gid=1
        var hashData = photoswipeParseHash();
        if (hashData.pid && hashData.gid) {
            openPhotoSwipe(hashData.pid, galleryElements[hashData.gid - 1], true, true);
        }
    },
    downloadCall: function (args) {
        var name = args.filename;
        var id = name.split(",")[0];
        $("#" + id).show();
        if (args.isfinish) {
            common.showTip("下载完成");
            $('.' + id).css('width', "70%");
            var path = args.filepath;
            type = name.split(".").pop();
            $("#" + id).removeClass(id);
            setTimeout(function () {
                $("#" + id).hide();
            }, 2000);
            //xiaz
            detail.recordCurrentUserAttachDownloadFiles(name, args.savePath, id, type, args.url, "");
            //最后打开文件
            $file.open({
                "filename": name,//文件全路径
                "filetype": type,
                "filepath": path
            });
        } else {
            var percent = parseInt(args.percent) * 0.75;
            console.log(args.percent + ",percent===" + percent);
            $('.' + id).css('width', percent + "%");
        }
    },
    errorFunction: function (res) {
        alert(res);
    },

    openfile: function (filetype, filepath, filename) {
        $file.open({
            "filename": filename,//文件全路径
            "filetype": filetype,
            "filepath": filepath
        })
    },
    downloadDocx: function (url, filepath, filename) {
        //开始了
        var getNetworkInfo = JSON.parse($net.getNetworkInfo());
        // //判断是否为wifi连接，
        if (getNetworkInfo.Type == "Wifi" || getNetworkInfo.Type == "WiFi") {
            $file.download({
                "url": url,
                "locate": filepath,
                "filename": filename,
                "override": "true",
                "callback": "detail.downloadCall()",
                "error": "detail.errorFunction()"
            });
        } else {
            common.showConfirm("您未链接Wi-Fi，确定使用流量下载附件吗？", function () {
                $file.download({
                    "url": url,
                    "locate": filepath,
                    "filename": filename,
                    "override": "true",
                    "callback": "detail.downloadCall()",
                    "error": "detail.errorFunction()"
                });
            });

        }
    },
    //记录附件下载的公共函数
    recordCurrentUserAttachDownloadFiles: function (fileName, savePath, id, type, url, thisFileSize) {
        //当前年月日计算
        var myDate = new Date();
        //年
        var att_year = myDate.getFullYear();
        //获取当前月份
        var att_month = parseInt(myDate.getMonth()) + 1;
        //获取当前日
        var att_day = myDate.getDate();

        //文件大小
        var fileSize = 0;
        if (thisFileSize == "" || thisFileSize == undefined) {
            //下载的文件信息
            var savePathInfo = $file.getFileInfo(savePath);
            if (typeof(savePathInfo) == "string") {
                fileSize = common.strToJson(savePathInfo).size;
            } else {
                fileSize = savePathInfo.size;
            }
            fileSize = common.calcFileSize(fileSize);
        } else {
            fileSize = thisFileSize;
        }
        //保存当前信息到本地存储当中去
        var thisFileInfo = {
            "att_day": parseInt(att_day) < 10 ? "0" + att_day : att_day,
            "att_month": parseInt(att_month) < 10 ? "0" + att_month : att_month,
            "att_year": att_year,
            "filename": fileName,
            "filesize": fileSize,
            "fileurl": url,
            "fname": fileName.split(",")[1].substring(0, fileName.split(",")[1].lastIndexOf(".")),
            "pk_attachment": id,
            "pk_business": "",
            "upload_type": type
        };
        //取得当前的json串值
        var currentUserAttachDownloadFiles = common.strToJson(window.localStorage.currentUserAttachDownloadFiles);
        if (typeof(currentUserAttachDownloadFiles) == "undefined") {
            currentUserAttachDownloadFiles = [];
        }
        //从0开始
        var i = 0;
        for (i = 0; i < currentUserAttachDownloadFiles.length; i++) {
            console.log(currentUserAttachDownloadFiles[i].fname);
            if (thisFileInfo.pk_attachment == currentUserAttachDownloadFiles[i].pk_attachment) {
                console.log("已经存在");
                break;
            }
        }
        if (i == currentUserAttachDownloadFiles.length) {
            currentUserAttachDownloadFiles.push(thisFileInfo);
            //保存到本地
            window.localStorage.currentUserAttachDownloadFiles = JSON.stringify(currentUserAttachDownloadFiles);
        }
    },
    /**
     * each page
     */
    initialize: function () {
        common.showLoading();
        //绑定事件
        detail.bindEvent();
        //路由绑定，覆盖首页设定路由
        detail.bindRout();
        //加载数据
        detail.loadData();
        //定义页面列表高度
        $("#detail_content").css("min-height", $(window).height() - $("#header").height());
        /*<script src="cordova.js"></script>
         <script src="js/Frameworks/iuapmobile.frameworks.core.js"></script>
         <script src="js/summer.js"></script>*/
        //动态异步加载cordova内容
        // var version = "?version=" + common.version;
    }
};